<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use Exception;
use fast\Tree;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Session;

/**
 * 佣金规则
 *
 * @icon fa fa-circle-o
 */
class Commissionrules extends Backend
{

    /**
     * Commissionrules模型对象
     * @var \app\common\model\Commissionrules
     */
    protected $model = null;
    protected $address = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Commissionrules;

        $commission_address=Session::get("commission_address");
        if(empty($commission_address)){
            $tree = Tree::instance();
            $tree->init(collection(\app\common\model\Area::field("id,pid,name,mergename,level")->order("id","asc")->select())->toArray(), 'pid');
            $commission_address= $tree->getTreeList($tree->getTreeArray(0), "name");
            foreach ($commission_address as &$item) {
                $item = str_replace('&nbsp;', ' ', $item);
            }
            unset($item);
            Session::set("commission_address",$commission_address );
        }
        $this->assignconfig("commiss", ['id' => 1]);
        $this->address=$commission_address;
    }

    protected function check($params,$ids=0){
        $data=[
            ['address', 'require', '区域不能为空'],
            ['name', 'require', '规则名称不能为空'],
            ['goods_smoke', 'require', '平台对商户本地商品单独抽佣不能为空'],
            ['favourable', 'require', '平台对用户优惠不能为空'],
            ['region_divide', 'require', '区域分佣不能为空'],
            ['merchant_smoke', 'require', '平台对商户核销抽佣不能为空'],
            ['kabaw_divide_profit', 'require', '卡包区域分佣不能为空'],
        ];
        if($ids){
            array_shift($data);
            array_values($data);
        }
        $validate = new \think\Validate($data);
        if (!$validate->check($params)) {
            $this->error('提交失败：' . $validate->getError());
        }
        $str="";
        if($ids>1 || empty($ids)){
            if(isset($params["address"]) && !empty($params["address"])&& !empty($params["address"][0])){
                foreach ($params["address"] as $k=>&$v){
                    $address=explode(",",$v);
                    $v=$address[1].$address[2].$address[3];
                    if(empty($k)){
                        $str.=$v;
                    }else{
                        $str.=",".$v;
                    }
                    if(!empty($ids)){
                        $address_rules=$this->model->where('FIND_IN_SET("'.$str.'", address)')->where("id <> ".$ids)->find();
                    }else{
                        $address_rules=$this->model->where('FIND_IN_SET("'.$str.'", address)')->find();
                    }
                    if(!empty($address_rules)) $this->error($str."已存在规则");
                }
            }
        }
        return ["code"=>"200","str"=>$str];
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $this->assign("address",$this->address);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        $res=$this->check($params);
        if($res["code"]!=200) return $res;
        Db::startTrans();
        try {
            $params["address"]=$res["str"];
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            foreach ($this->address as &$v){
                $v["checked"]=false;
                if($v["level"]==3){
                    $mergename=explode(",",$v["mergename"]);
                    $commiss=$this->model->field("1")->where(["id"=>$ids])->where('FIND_IN_SET("'.$mergename[1].$mergename[2].$mergename[3].'", address)')->find();
                    if(!empty($commiss)) $v["checked"]=true;
                }
            }
            $this->assign("address",$this->address);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        $res=$this->check($params,$ids);
        if($res["code"]!=200) return $res;
        Db::startTrans();
        try {
            if(isset($params["address"]) && !empty($params["address"][0])){
                $params["address"]=$res["str"];
            }else{
                unset($params["address"]);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


}
